"""
网络服务模块
提供网络相关的服务功能
"""

import subprocess
import re
import socket
import netifaces
import logging

logger = logging.getLogger(__name__)

def get_ip_address():
    """获取主IP地址"""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        # 不需要真正连接
        s.connect(('10.255.255.255', 1))
        ip = s.getsockname()[0]
    except Exception:
        ip = '127.0.0.1'
    finally:
        s.close()
    return ip

def get_network_interfaces():
    """获取网络接口列表"""
    try:
        interfaces = []
        
        for iface in netifaces.interfaces():
            # 排除虚拟接口
            if iface.startswith('lo'):
                continue
                
            addrs = netifaces.ifaddresses(iface)
            
            interface_info = {
                'name': iface,
                'mac': '',
                'ipv4': [],
                'ipv6': [],
                'active': False
            }
            
            # 获取MAC地址
            if netifaces.AF_LINK in addrs:
                interface_info['mac'] = addrs[netifaces.AF_LINK][0]['addr']
                
            # 获取IPv4地址
            if netifaces.AF_INET in addrs:
                for addr in addrs[netifaces.AF_INET]:
                    interface_info['ipv4'].append({
                        'address': addr.get('addr', ''),
                        'netmask': addr.get('netmask', ''),
                        'broadcast': addr.get('broadcast', '')
                    })
                    
            # 获取IPv6地址
            if netifaces.AF_INET6 in addrs:
                for addr in addrs[netifaces.AF_INET6]:
                    interface_info['ipv6'].append({
                        'address': addr.get('addr', ''),
                        'netmask': addr.get('netmask', '')
                    })
            
            # 检查接口状态
            interface_info['active'] = bool(interface_info['ipv4'] or interface_info['ipv6'])
            
            # 添加接口名称特性(有线/无线)
            if iface.startswith('wlan') or iface.startswith('wlp'):
                interface_info['type'] = 'wireless'
            elif iface.startswith('eth') or iface.startswith('enp'):
                interface_info['type'] = 'ethernet'
            else:
                interface_info['type'] = 'other'
            
            interfaces.append(interface_info)
        
        return interfaces
        
    except Exception as e:
        logger.error(f"获取网络接口失败: {str(e)}")
        return []

def scan_wifi_networks():
    """扫描WiFi网络"""
    try:
        # 找出无线接口名
        wireless_iface = None
        for iface in netifaces.interfaces():
            if iface.startswith('wlan') or iface.startswith('wlp'):
                wireless_iface = iface
                break
                
        if not wireless_iface:
            raise Exception('No wireless interface found')
        
        # 使用nmcli扫描WiFi
        cmd = ['nmcli', '-t', '-f', 'SSID,SIGNAL,SECURITY', 'device', 'wifi', 'list', '--rescan', 'yes']
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        
        if process.returncode != 0:
            # 尝试使用iwlist
            cmd = ['iwlist', wireless_iface, 'scan']
            process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = process.communicate()
            
            if process.returncode != 0:
                raise Exception(f'WiFi scanning failed: {stderr.decode()}')
            
            # 解析iwlist输出
            wifi_list = []
            current_network = {}
            for line in stdout.decode().split('\n'):
                line = line.strip()
                ssid_match = re.search(r'ESSID:"([^"]*)"', line)
                if ssid_match:
                    if current_network and 'ssid' in current_network:
                        wifi_list.append(current_network)
                    current_network = {'ssid': ssid_match.group(1), 'signal': 0, 'security': ''}
                    
                signal_match = re.search(r'Quality=(\d+)/(\d+)', line)
                if signal_match and current_network:
                    quality = int(signal_match.group(1)) / int(signal_match.group(2)) * 100
                    current_network['signal'] = int(quality)
                    
                if 'WPA2' in line and current_network:
                    current_network['security'] = 'WPA2'
                elif 'WPA' in line and current_network and 'security' not in current_network:
                    current_network['security'] = 'WPA'
                elif 'WEP' in line and current_network and 'security' not in current_network:
                    current_network['security'] = 'WEP'
            
            if current_network and 'ssid' in current_network:
                wifi_list.append(current_network)
        else:
            # 解析nmcli输出
            wifi_list = []
            for line in stdout.decode().split('\n'):
                if not line:
                    continue
                parts = line.split(':')
                if len(parts) >= 3:
                    wifi_list.append({
                        'ssid': parts[0],
                        'signal': int(parts[1]) if parts[1].isdigit() else 0,
                        'security': parts[2] if parts[2] else 'open'
                    })
        
        # 过滤重复的SSID，保留信号最强的
        filtered_list = {}
        for network in wifi_list:
            ssid = network['ssid']
            if not ssid:  # 忽略空SSID
                continue
                
            if ssid not in filtered_list or network['signal'] > filtered_list[ssid]['signal']:
                filtered_list[ssid] = network
        
        # 按信号强度排序
        sorted_list = sorted(filtered_list.values(), key=lambda x: x['signal'], reverse=True)
        
        return sorted_list
        
    except Exception as e:
        logger.error(f"扫描WiFi失败: {str(e)}")
        return []

def connect_wifi(ssid, password=None):
    """连接WiFi网络"""
    try:
        # 使用nmcli连接WiFi
        if password:
            cmd = ['nmcli', 'device', 'wifi', 'connect', ssid, 'password', password]
        else:
            cmd = ['nmcli', 'device', 'wifi', 'connect', ssid]
            
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        
        if process.returncode == 0:
            logger.info(f"成功连接到WiFi: {ssid}")
            return True, f'Connected to {ssid}'
        else:
            error_msg = stderr.decode()
            logger.error(f"连接WiFi失败: {error_msg}")
            return False, error_msg
            
    except Exception as e:
        logger.error(f"连接WiFi异常: {str(e)}")
        return False, str(e)

def disconnect_wifi():
    """断开WiFi连接"""
    try:
        # 查找当前WiFi连接
        cmd = ['nmcli', '-t', '-f', 'NAME,TYPE,DEVICE', 'connection', 'show', '--active']
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
        
        if process.returncode != 0:
            return False, 'Failed to get active connections'
        
        # 断开所有WiFi连接
        for line in stdout.decode().split('\n'):
            if '802-11-wireless' in line:
                parts = line.split(':')
                if len(parts) >= 1:
                    connection_name = parts[0]
                    cmd = ['nmcli', 'connection', 'down', connection_name]
                    subprocess.run(cmd)
        
        logger.info("WiFi连接已断开")
        return True, 'WiFi disconnected'
        
    except Exception as e:
        logger.error(f"断开WiFi失败: {str(e)}")
        return False, str(e) 